package com.cucn.ingmall.seckill.scheduled;

import com.cucn.ingmall.seckill.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 秒杀商品定时上架服务
 * 每天晚上3点,上架最近三天秒杀商品
 * 当天 00:00:00 - 23:59:59
 * 明天 00:00:00 - 23:59:59
 * 后天 00:00:00 - 23:59:59
 *
 * @author KouChaoJie
 * @since: 2022/2/13 17:15
 */
@Slf4j
@Service
public class SeckillSkuScheduled {
    @Resource
    private SeckillService seckillService;
    @Resource
    private RedissonClient redissonClient;

    public static final String UPLOAD_LOCK = "seckill:upload:lock";

    //KouTODO:2022/2/14 13:39 Kou 幂等性处理
    @Scheduled(cron = "0 * * * * ? ")
    public void uploadSeckillSkuLastThreeDays() {
        //1.重复上架无需处理
        //上架最新三天秒杀商品
        log.info("上架秒杀商品信息....");
        //分布式锁
        RLock lock = redissonClient.getLock(UPLOAD_LOCK);
        lock.lock(10L, TimeUnit.SECONDS);
        try {
            seckillService.uploadSeckillLastThreeDays();
        } finally {
            lock.unlock();
        }
    }
}
